<?php
/**
 * Class OrderReceive
 * Desc  订单接单Controller
 * Create on 2021/8/25 16:15
 * Create by wangyafang
 */

namespace app\api\controller\xyb;


use addons\xyb\library\Wxapp;
use addons\xyb\XypHelper;
use app\api\model\xyb\OrderComplaint;
use \app\api\model\xyb\UserPlat;
use \app\api\model\xyb\WechatOfficialAccount;
use app\api\service\OrdersService;
use app\api\service\TemplateService;
use app\api\service\UsersService;
use app\common\model\xyb\AdminBelong;
use app\common\model\xyb\MiniPushMessageLog;
use think\Cache;
use think\cache\driver\Redis;
use think\Db;
use app\api\model\xyb\Order;
use app\api\model\xyb\UserReceive;

class OrderReceive extends Base
{
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\api\model\xyb\OrderReceive();
    }

    /**
     *
     * status
     *  0：待付款，
     *  1：已付款 接单员可接单；
     *  2：已接单 接单员接单成功，待取件，
     *  8：已取件（确认收件）待送达；
     *  7：已送达 待发布人确认完成；
     *  3：已完成 发布人完成，金额分成，
     *  4：已取消；，
     *  6：已退款；
     * desc:添加接受订单记录 status = 2
     * param:
     * 订单id:order_id
     * 发布人id:public_id
     * 接受人id:receive_id
     */
    public function receiving_orders()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        if(!$order_id = (int)$this->request->param('id')){
            $this->error('参数错误');
        }
        $cache_key = 'receive_order_'.$order_id;
        if(Cache::get($cache_key)){
            $this->error('手慢了，订单未抢到');
        }
        $operate_cache_key = '__operate_order_'.$order_id;
        if(Cache::get($operate_cache_key)){
            $this->error('订单正在操作中，请稍后再试！');
        }
        Cache::set($cache_key, $order_id, 5);
        $users = $this->getAuthUsers();
        if(!$agent_info = UsersService::getCommunityWhereUsersLocated($users->id)){
            Cache::rm($cache_key);
            $this->error('用户没有权限');
        }
        if(!$agent_info->is_rider){
            Cache::rm($cache_key);
            $this->error('非接单员不可接单');
        }
        if(!$agent_info->is_rider || !$agent_info->rider_info){
            Cache::rm($cache_key);
            $this->error('非接单员不可接单');
        }
        if(!isset($agent_info->is_rider_stated) || !$agent_info->is_rider_stated){
            Cache::rm($cache_key);
            $this->error('接单员已封禁');
        }
        if(!isset($agent_info->is_rider_receiving) || !$agent_info->is_rider_receiving){
            Cache::rm($cache_key);
            $this->error('接单员未上线');
        }

        if(!$orderObj = (new Order())->get($order_id)){
            Cache::rm($cache_key);
            $this->error('订单不存在');
        }
        if((int)$orderObj->status !== 1){
            Cache::rm($cache_key);
            $this->error('已被别人接单了');
        }
        if((new UserReceive())->where(['agent_id'=>$orderObj->agent_id, 'user_id'=>$users->id, 'status'=>'hidden'])->value('id')) {
            Cache::rm($cache_key);
            $this->error('接单功能被禁用,请联系代理解禁');
        }
//        $default_receive_id = OrdersService::getAgentServiceDefaultReceiveId($orderObj->agent_id, $orderObj->type);
//        if($default_receive_id && ($default_receive_id != $this->auth->id)) {
//            $this->error('只有默认接单员能接单');
//        }
        if($this->model->where(['order_id'=>$order_id, 'receive_id'=>$users->id])->value('id')) {
            Cache::rm($cache_key);
            $this->error('已经接这个单了');
        }

        if($orderObj['user_id'] == $this->auth->id) {
            $this->error('不能接自己发的单');
        }
        $where['order_id'] = array('eq', $order_id);
        $where['receive_id'] = array('neq',$users->id);
        $where['status'] = array('not in', [0, 4, 6]);
        if($this->model->where($where)->value('id')) {
            Cache::rm($cache_key);
            $this->error('订单被别人接过了');
        }
        Db::startTrans();
        $time = time();
        try {
            $pick_code = mt_rand(1111, 9999);
            $res = (new Order())->save(
                ['receive_id'=>$users->id, 'status'=>2, 'receive_time'=>$time,'receiving_id'=>$users->id,'pick_code'=>$pick_code],
                ['id'=>$order_id, 'status' => 1,'receive_id'=>0]
            );
            if(!$res) {
                Db::rollback();
                Cache::rm($cache_key);
                $this->error('接单失败');
            }
            $res = $this->model->save(['order_id'=>$order_id, 'public_id'=>$orderObj->user_id, 'receive_id'=>$users->id, 'status'=>0]);
            if(!$res) {
                Db::rollback();
                Cache::rm($cache_key);
                $this->error('接单失败');
            }
            TemplateService::sendTemplateReceiving($orderObj->agent_id, $order_id);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Cache::rm($cache_key);
            $this->error($e->getMessage());
        }
        Cache::rm($cache_key);
        $this->success('接单成功');
    }

    public function dispatch_orders(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        if(!$receive_id =  (int)$this->request->param('user_id')){
            $this->error('参数错误');
        }
        if(!$order_id = (int)$this->request->param('order_id')){
            $this->error('参数错误');
        }
        $operate_cache_key = '__operate_order_'.$order_id;
        if(Cache::get($operate_cache_key)){
            $this->error('订单正在操作中，请稍后再试！');
        }
        $cache_key = 'receive_order_'.$order_id;
        if(Cache::get($cache_key)){
            $this->error('手慢了，订单已被接单');
        }
        Cache::set($cache_key, $order_id, 5);
        if(!$agent_info = UsersService::getCommunityWhereUsersLocated($receive_id)){
            Cache::rm($cache_key);
            $this->error('用户没有权限');
        }
        if(!$agent_info->is_rider){
            Cache::rm($cache_key);
            $this->error('非接单员不可接单');
        }
        if(!$agent_info->is_rider || !$agent_info->rider_info){
            Cache::rm($cache_key);
            $this->error('非接单员不可接单');
        }
        if(!isset($agent_info->is_rider_stated) || !$agent_info->is_rider_stated){
            Cache::rm($cache_key);
            $this->error('接单员已封禁');
        }
        if(!isset($agent_info->is_rider_receiving) || !$agent_info->is_rider_receiving){
            Cache::rm($cache_key);
            $this->error('接单员未上线');
        }

        if(!$orderObj = (new Order())->get($order_id)){
            Cache::rm($cache_key);
            $this->error('订单不存在');
        }
        if((int)$orderObj->status !== 1){
            Cache::rm($cache_key);
            $this->error('已被别人接单了');
        }
        if((new UserReceive())->where(['agent_id'=>$orderObj->agent_id, 'user_id'=>$receive_id, 'status'=>'hidden'])->value('id')) {
            Cache::rm($cache_key);
            $this->error('接单功能被禁用,请联系代理解禁');
        }
 //       $default_receive_id = OrdersService::getAgentServiceDefaultReceiveId($orderObj->agent_id, $orderObj->type);
//        if($default_receive_id && ($default_receive_id != $this->auth->id)) {
//            $this->error('只有默认接单员能接单');
//        }
        if($this->model->where(['order_id'=>$order_id, 'receive_id'=>$receive_id])->value('id')) {
            Cache::rm($cache_key);
            $this->error('已经接这个单了');
        }

        if($orderObj['user_id'] == $this->auth->id) {
            $this->error('不能接自己发的单');
        }
        $where['order_id'] = array('eq', $order_id);
        $where['receive_id'] = array('neq', $receive_id);
        $where['status'] = array('neq', 4);
        if($this->model->where($where)->value('id')) {
            Cache::rm($cache_key);
            $this->error('订单被别人接过了');
        }
        Db::startTrans();
        $time = time();
        try {
            $pick_code = mt_rand(1111, 9999);
            $res = (new Order())->save(
                ['receive_id'=>$receive_id, 'status'=>2, 'receive_time'=>$time,'receiving_id'=>$receive_id,'pick_code'=>$pick_code],
                ['id'=>$order_id, 'status' => 1,'receive_id'=>0]
            );
            if(!$res) {
                Db::rollback();
                Cache::rm($cache_key);
                $this->error('接单失败');
            }
            $res = $this->model->save(['order_id'=>$order_id, 'public_id'=>$orderObj->user_id, 'receive_id'=>$receive_id, 'status'=>0]);
            if(!$res) {
                Db::rollback();
                Cache::rm($cache_key);
                $this->error('接单失败');
            }
            TemplateService::sendTemplateReceiving($orderObj->agent_id, $order_id);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Cache::rm($cache_key);
            $this->error($e->getMessage());
        }
        Cache::rm($cache_key);
        $this->success('派单成功');
    }

    public function order_reward(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $orderModel = (new Order());
        $order_id = (int)$this->request->param('id');
        $reward = (int)$this->request->param('reward');
        Db::startTrans();
        $time = time();
        try {
            $orderModel->where( ['id'=>$order_id])->update(
                ['reward'=>$reward, 'updatetime'=>$time,'total_fee'=>Db::raw("total_fee+{$reward}")]
            );
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('订单支付成功',[
            'payment' => [],
            'pay_stated' => true
        ]);
    }

    /**
     * desc:确认收件  status = 8
     * param:
     * 订单id:order_id
     * 发布人id:public_id
     * 接受人id:receive_id
     */
    public function confirm_package_orders(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $orderModel = (new Order());
        $users = $this->getAuthUsers();
        $order_id = (int)$this->request->param('id');
        $picture = $this->request->param('picture','');
        $notes = $this->request->param('notes','');
        if($notes == 'null' || $notes == 'undefined'){
            $notes = '';
        }
        $orderObj = $orderModel->get($order_id);

        if((int)$orderObj->status !== 2){
            $this->error('订单未接单');
        }
        if($orderObj->receive_id != $users->id){
            $this->error('你不是接单人');
        }
        Db::startTrans();
        $time = time();
        try {
            $orderModel->where( ['id'=>$order_id, 'status' => 2])->update(
                ['status'=>8,'package_time'=>$time,'package_picture'=>$picture,'notes'=>$notes]
            );
            TemplateService::sendTemplatePackage($orderObj->agent_id, $order_id);
            Db::commit();
        } catch (\Exception $e) {
            // $redis->lpush($domain.'_order_number_'.$order_id,1);
            //扣库存失败，把库存加回
            // $redis->sRem($domain.'_user_receive_order_list_'.$order_id, $users->id);
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('收件成功');
    }

    /**
     * desc:确认送达 status = 7
     * param:
     * 订单id:order_id
     * 发布人id:public_id
     * 接受人id:receive_id
     */
    public function confirm_delivery_orders(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        $order_id = (int)$this->request->param('id');
        $picture = $this->request->param('picture');
        $pick_code = (int)$this->request->param('pick_code');
        $orderObj = (new Order())->get($order_id);
        if((int)$orderObj->status !== 8){
            $this->error('订单未取件');
        }
        $confirm_complete = false;
        if( OrdersService::getAgentAdminBelongIspickCode($orderObj->agent_id)){
            $confirm_complete = true;
            if((int)$orderObj->pick_code !== $pick_code){
                $this->error('收货码错误');
            }
        }
        if($orderObj->receive_id != $users->id){
            $this->error('你不是接单人');
        }
        Db::startTrans();
        $time = time();
        try {
            (new Order())->save(
                ['status'=>7, 'send_time'=>$time, 'send_picture'=>$picture],
                ['id'=>$order_id, 'status' => 8]
            );
            $this->model->save([ 'status'=>1,'updatetime'=>$time], ['order_id'=>$order_id, 'receive_id'=>$users->id]);
            TemplateService::sendTemplateDelivery($orderObj->agent_id, $order_id);
            if($confirm_complete === true){
                if(!OrdersService::confirmCompleteOrders($orderObj)){
                    Db::rollback();
                    $this->error('订单确认失败');
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('送达成功');
    }

    /**
     * desc:确认完成订单 status = 3
     * param:
     * 订单id:order_id
     * 发布人id:public_id
     * 接受人id:receive_id
     */
    public function confirm_complete_orders(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        $order_id = (int)$this->request->param('id');
        $orderObj = (new Order())->get($order_id);
        if((int)$orderObj->status !== 7){
            $this->error('订单未送达');
        }
        if($orderObj->user_id != $users->id){
            $this->error('你不是发布人');
        }
        Db::startTrans();
        try {
            if(!OrdersService::confirmCompleteOrders($orderObj)){
                Db::rollback();
                $this->error('订单确认失败');
            }
          //  TemplateService::sendTemplateComplete($orderObj->agent_id, $order_id);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('订单完成成功');
    }

    /**
     * desc:评价订单 status = 3
     * param:
     * 订单id:order_id
     * 发布人id:public_id
     * 接受人id:receive_id
     */
    public function evaluate_orders(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        $order_id = (int)$this->request->param('id');
        $orderObj = (new Order())->get($order_id);
//        if((int)$orderObj->status !== 3){
//            $this->error('订单未确认，无法评论');
//        }
        $speed = (int)$this->request->param('speed', 5);
        $attitude = (int)$this->request->param('attitude', 5);
        if($orderObj->user_id != $users->id){
            $this->error('你不是发布人');
        }
        Db::startTrans();
        try {
            if(!OrdersService::evaluateOrders($orderObj->id, $orderObj->receive_id, $speed, $attitude)){
                Db::rollback();
                $this->error('订单评论失败');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('订单完成成功');
    }


    /**
     * desc:投诉订单 status = 3
     * param:
     * 订单id:order_id
     * 发布人id:public_id
     * 接受人id:receive_id
     */
    public function complaint_orders(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        $order_id = (int)$this->request->param('id');
        $orderObj = (new Order())->get($order_id);
        if(!$orderObj){
            $this->error('订单不存在');
        }
        $content = $this->request->param('content','');
        $picture = $this->request->param('picture', '');
        $tags = $this->request->param('tags', '');
        if($orderObj->user_id != $users->id){
            $this->error('你不是发布人');
        }
//        if($orderObj->is_complaint > 0){
//            $this->error('订单已投诉');
//        }
        Db::startTrans();
        try {
            if(!OrderComplaint::createOrderComplaint($orderObj, $content, $picture, $tags)){
                Db::rollback();
                $this->error('订单投诉失败');
            }
            Order::where('id', $order_id)->update(['is_complaint' => 1]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('订单投诉提交成功');
    }

    public function orders_complaint_detail(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $order_id = $this->request->param('id');
        $field = 'id,order_no,receive_id,user_id,status,type,start,destination,information,total_fee,reward,price,';
        $field .= 'express,remarks,annex_information_images,hope_arrive,pay,pay_time,receive_time,complete_time,cancel_time,';
        $field .= 'send_time,createtime,receive_limit,mobile,notes,send_picture,package_time,package_picture,pick_code,agent_id';
        $data = Db::name('xyb_order')->where('id', $order_id)->where('is_complaint', 1)->field($field)->find();
        if(!$data){
            $this->error('订单不存在');
        }
        $data['nickname'] = '';
        $data['avatar'] = '';
        $data['receiving_nickname'] = '';
        $data['receiving_avatar'] = '';
        $data['receiving_mobile'] = '';
        /*获取发布人的用户信息*/
        if($push_users = UsersService::getUsersFoundation($data['user_id'])){
            $data['nickname'] = $push_users['nickname'];
            $data['avatar'] =  $push_users['avatar'];
        }
        /*获取接单人的用户信息*/
        if($receiving_users = UsersService::getReceivingUsersFoundation($data['receive_id'],$data['agent_id'])){
            $data['receiving_nickname'] = $receiving_users['nickname'];
            $data['receiving_avatar'] =  $receiving_users['avatar'];
            $data['receiving_mobile'] =  $receiving_users['mobile'];
        }
        /*处理佣金*/
        $data['amount_items'] = OrdersService::CalculateOrdersRevenue($data);
        $data['receive_amount'] = $data['amount_items']['receive_amount'];
        /*处理状态信息*/
        $data['status_text'] = OrdersService::formatOrdersStatus($data['status']);
        if($data['notes'] == 'null' || is_null($data['notes'])){
            $data['notes'] = '';
        }
        /*处理时间*/
        $data['create_date'] = date("Y-m-d H:i:s", $data['createtime']);
        $data['pay_date'] = $data['pay_time'] ? date("Y-m-d H:i:s", $data['pay_time']) : '';
        $data['receive_date'] = $data['receive_time'] ? date("Y-m-d H:i:s", $data['receive_time']) : '';
        $data['package_date'] = $data['package_time'] ? date("Y-m-d H:i:s", $data['package_time']) : '';
        $data['send_date'] = $data['send_time'] ? date("Y-m-d H:i:s", $data['send_time']) : '';
        $data['complete_date'] = $data['complete_time'] ? date("Y-m-d H:i:s", $data['complete_time']) : '';
        $data['type_text'] = Order::getTypeNameTextName($data['type'],[]);
        $data['dateline_create_date'] = XypHelper::xyb_dateline($data['createtime']);//创建时间
        $data['annex_information_images'] = XypHelper::stringToArray($data['annex_information_images']);
        $data['send_picture'] = XypHelper::stringToArray($data['send_picture']);
        $data['package_picture'] = XypHelper::stringToArray($data['package_picture']);
        $data['express'] = !empty($data['express']) ? json_decode($data['express']) : [];
        $data['is_pick_code'] = OrdersService::getAgentAdminBelongIspickCode($data['agent_id']);
        $data['complaint'] = OrderComplaint::getOrderComplaint($order_id);
        $this->success('请求成功', $data);
    }

    public function complaint_orders_lists(){
        $users = $this->getAuthUsers();
        $agent_info = UsersService::getCommunityWhereUsersLocated($users->id);
        $status = $this->request->param('status', 0);
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);
        $field = [
            'xyb_order.id','xyb_order.user_id','xyb_order.receive_id','xyb_order.order_no','xyb_order.mobile',
            'xyb_order.type', 'xyb_order.information','xyb_order.total_fee','xyb_order.agent_id',
            'xyb_order.annex_information_images','xyb_order.agent_id','xyb_order.agent_id',
            'yx_xyb_order_complaint.status', 'yx_xyb_order_complaint.content','yx_xyb_order_complaint.picture',
            'yx_xyb_order_complaint.tags', 'yx_xyb_order_complaint.reply_content', 'yx_xyb_order_complaint.reply_time',
            'yx_xyb_order_complaint.reply_picture','yx_xyb_order_complaint.reject_reason'
        ];
        $query = OrderComplaint::join('xyb_order','yx_xyb_order_complaint.order_id = xyb_order.id')
            ->field($field)
            ->where('xyb_order.user_id', $users->id)
            ->where('xyb_order.is_complaint', 1);
        if($status){
            $query->where('yx_xyb_order_complaint.status', ($status - 1));
        }
        $query->page($page, $limit)->order('yx_xyb_order_complaint.id','desc');

        $lists = $query->select();
        $count = $query->count();
        foreach ($lists as $k=>$v) {
            $push_users = UsersService::getUsersFoundation($v['user_id']);
            $lists[$k]['dateline_create_date'] = XypHelper::xyb_dateline($v['createtime']);//创建时间
            $lists[$k]['receive_users'] = new \ArrayObject();
            $lists[$k]['nickname'] = $push_users['nickname'];
            $lists[$k]['avatar'] = $push_users['avatar'];
            $lists[$k]['annex_information_images'] = XypHelper::stringToArray($v['annex_information_images']);
            $lists[$k]['picture'] = XypHelper::stringToArray($v['picture']);
            $lists[$k]['reply_picture'] = XypHelper::stringToArray($v['reply_picture']);
            $lists[$k]['type_text'] = Order::getTypeNameTextName($k['type'],[]);
            $lists[$k]['status_text'] = OrdersService::formatOrdersStatus($v['status']);
            $lists[$k]['express'] = !empty($k['express']) ? json_decode($k['express']) : [];
            if($v['receive_id']){
                $lists[$k]['receive_users'] = UsersService::getReceivingUsersFoundation($v['receive_id'],$v['agent_id']);
            }
        }
        $this->success('请求成功',['total'=>$count,'data'=>$lists]);
    }

















    public function rider_homepage(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        $order_id = (int)$this->request->param('id');
        $orderObj = (new Order())->get($order_id);
        if((int)$orderObj->status !== 3){
            $this->error('订单未确认，无法评论');
        }
        $speed = (int)$this->request->param('speed', 5);
        $attitude = (int)$this->request->param('attitude', 5);
        if($orderObj->user_id != $users->id){
            $this->error('你不是发布人');
        }
        Db::startTrans();
        try {
            if(!OrdersService::evaluateOrders($orderObj->id, $orderObj->receive_id, $speed, $attitude)){
                Db::rollback();
                $this->error('订单确认失败');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('订单完成成功');
    }
    /**
     * desc:添加接受订单记录
     * param:
     * 订单id:order_id
     * 发布人id:public_id
     * 接受人id:receive_id
     */
    public function add()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        $order_id = (int)$this->request->param('id');
        $orderObj = (new Order())->get($order_id);
        if($orderObj->status !== 1){
            $this->error('已被别人接单了');
        }
        $param = $this->request->param();
        $param['user_id'] = $this->auth->id;
        if($param['app_plat'] == 'MP-WEIXIN' && ($this->configObj['subscribe'] == '1')) {
            $unionid = (new UserPlat())
                ->alias('u_p')
                ->where('u_p.user_id',$param['user_id'])
                ->join('xyb_user_wechat u_w','u_w.id = u_p.wechat_id')
                ->value('u_w.unionid');
            $wechatOfficialAccountInfo = (new WechatOfficialAccount())->where('unionid',$unionid)->find();
            if(!$wechatOfficialAccountInfo || ($wechatOfficialAccountInfo['subscribe'] == 0)) {
                $this->error('请先关注公众号');
            }
        }

        if((new UserReceive())->where(['agent_id'=>$param['agent_id'], 'user_id'=>$users->id, 'status'=>'hidden'])->value('id')) {
            $this->error('接单功能被禁用,请联系代理解禁');
        }
        $default_receive_id = OrdersService::getAgentServiceDefaultReceiveId($orderObj->agent_id, $orderObj->type);
        if($default_receive_id && ($default_receive_id != $this->auth->id)) {
            $this->error('只有默认接单员能接单');
        }
        if($this->model->where(['order_id'=>$order_id, 'receive_id'=>$users->id])->value('id')) {
            $this->error('已经接这个单了');
        }

//        if($orderObj['user_id'] == $this->auth->id) {
//            $this->error('不能接自己发的单');
//        }
        $where['order_id'] = array('eq', $order_id);
        $where['receive_id'] = array('neq',$users->id);
        $where['status'] = array('neq',4);
        if($this->model->where($where)->value('id')) {
            $this->error('订单被别人接过了');
        }
        $redis = new Redis();
        $redis = $redis->handler();
        $domain = $_SERVER['HTTP_HOST'];
        if ($redis->sismember($domain.'_user_receive_order_list_'.$order_id,$this->auth->id)) {
            $this->error('已经接这个单了');
        }
        $count=$redis->rpop($domain.'_order_number_'.$order_id);
        //每次从num取出1,防止超卖
        if($count==0) {
            $this->error('订单被接了');
        }
        $redis->sAdd($domain.'_user_receive_order_list_'.$order_id, $users->id);

        Db::startTrans();
        $time = time();
        try {
            (new Order())->save(
                ['receive_id'=>$users->id, 'status'=>2, 'receive_time'=>$time],
                ['id'=>$order_id]
            );
            $this->model->save(['order_id'=>$order_id, 'public_id'=>$orderObj->user_id, 'receive_id'=>$users->id, 'status'=>0]);
            Db::commit();
        } catch (\Exception $e) {
            $redis->lpush($domain.'_order_number_'.$order_id,1);
            //扣库存失败，把库存加回
            $redis->sRem($domain.'_user_receive_order_list_'.$order_id, $users->id);
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('接单成功');
    }

    /**
     * desc:接单员确认送达
     */
    public function receive_confirm_arrive()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $order_id = 1;
        $param = $this->request->param();
        $orderObj = (new Order())->get($order_id);
        if($orderObj['receive_id'] == 0) {
            $this->error('已退单');
        }
        $reveice_id = $this->auth->id;
        try {
            $where['receive_id'] = $reveice_id;
            $where['order_id'] = $order_id;
            $where['app_plat'] = $param['app_plat'];
            $this->model->where($where)->update(['status'=>'1', 'updatetime'=>time(),]);
            (new Order())->save(['status'  => 7, 'expiretime'=>time()+86400,],['id' => $order_id]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $redis = new Redis();
        $redis = $redis->handler();
        $domain = $_SERVER['HTTP_HOST'];
        $redis->sRem($domain.'_user_receive_order_list_'.$order_id,$this->auth->id);
        $orderInfo = (new Order())->get($order_id);

        if($orderInfo['type'] == 1) {
            $orderInfo['tips'] = '校园跑腿';
        }else if($orderInfo['type'] == 2) {
            $orderInfo['tips'] = '快递代取';
        }else if($orderInfo['type'] == 4) {
            $orderInfo['tips'] = '租借服务';
        }
        $orderReceiveInfo = $this->model->where('order_id',$orderInfo['id'])->find();
        $wechatInfo = (new UserPlat())->alias('plat')
            ->where([
                'plat.user_id'=>$orderReceiveInfo['public_id'],
            ])
            ->join('xyb_user_wechat wechat','plat.wechat_id = wechat.id')
            ->field('wechat.openid,wechat.nickname,plat.mobile')->find();
        $recevieInfo = (new UserPlat())->alias('plat')
            ->where([
                'plat.user_id'=>$orderReceiveInfo['receive_id'],
            ])
            ->join('xyb_user_wechat wechat','plat.wechat_id = wechat.id')
            ->field('wechat.openid,wechat.nickname,plat.mobile')->find();
        $data = [
            'openid'=>$wechatInfo['openid'],
            'form_id'=>13412,
            'template_id' => $this->configObj->delivery_complete,
            'page'=>'/pages/Component/Module/Campus/Program/Order/myorder/index',
            'data'=>[
                'thing1' => array(
                    'value'=> $orderInfo['tips']
                ),
                'character_string2' => array(
                    'value'=>$orderInfo['order_no']
                ),
                'thing4' => array(
                    'value'=>$recevieInfo['nickname']
                ),
                'phone_number8' => array(
                    'value'=>$recevieInfo['mobile']
                ),
                'time6' => array(
                    'value'=>date('Y-m-d H:i:s',time()),
                )
            ],
        ];
        $push_result = (new WechatMiniPush())->PushOneMsg($data);
        $push_result = json_decode($push_result,true);
        $order_result = $orderInfo;
        $order_type = '校园跑腿';
        if($order_result['type'] == 1) {
            $order_type = '校园跑腿';
        }else if($order_result['type'] == 2) {
            $order_type= '快递代取';
        }else if($order_result['type'] == 4) {
            $order_type = '租借服务';
        }
        //查出校区
        $agent_info = (new AdminBelong())->where('admin_id',$order_result['agent_id'])->value('agent_area');
        if($push_result['errcode'] == 0) {
            $userWechatObj = (new UserPlat())->alias('plat')
                ->where('plat.user_id',$orderInfo['receive_id'])
                ->join('xyb_user_wechat wechat','wechat.id = plat.wechat_id')
                ->field('wechat.nickname,wechat_id,wechat.openid,wechat.unionid')
                ->find();
            $insert_data = [
                'type'=>'送达通知',
                'agent_id'=>$order_result['agent_id'],
                'order_id'=>$order_result['id'],
                'errmsg'=>$push_result['errmsg'],
                'user_id'=>$orderInfo['user_id'],
                'wechat_id'=>$userWechatObj['wechat_id'],
                'desc'=>'订单id:'.$order_result['id'].'送达成功通知给给发布人，微信昵称:'.$userWechatObj['nickname'].'消息成功,校区名称:'.$agent_info.'--订单类型：'.$order_type,
                'createtime'=>time(),
                'openid'=>$userWechatObj['openid'],
                'unionid'=>$userWechatObj['unionid'],
                'data'=>json_encode([
                    'thing1' => array(
                        'value'=> $orderInfo['tips']
                    ),
                    'character_string2' => array(
                        'value'=>$orderInfo['order_no']
                    ),
                    'thing4' => array(
                        'value'=>$recevieInfo['nickname']
                    ),
                    'phone_number8' => array(
                        'value'=>$recevieInfo['mobile']
                    ),
                    'time6' => array(
                        'value'=>date('Y-m-d H:i:s',time()),
                    )
                ]),
                'status_text'=>'推送成功',
            ];
            (new MiniPushMessageLog())->create($insert_data);
        } else {
            $userWechatObj = (new UserPlat())->alias('plat')
                ->where('plat.user_id',$orderInfo['receive_id'])
                ->join('xyb_user_wechat wechat','wechat.id = plat.wechat_id')
                ->field('wechat.nickname,wechat_id,wechat.openid,wechat.unionid')
                ->find();
            $insert_data = [
                'type'=>'送达通知',
                'agent_id'=>$order_result['agent_id'],
                'order_id'=>$order_result['id'],
                'errmsg'=>$push_result['errmsg'],
                'user_id'=>$orderInfo['user_id'],
                'wechat_id'=>$userWechatObj['wechat_id'],
                'desc'=>'订单id:'.$order_result['id'].'送达失败通知给给发布人，微信昵称:'.$userWechatObj['nickname'].'消息失败,失败原因:'.$push_result['errmsg'].'校区名称:'.$agent_info.'--订单类型：'.$order_type,
                'createtime'=>time(),
                'openid'=>$userWechatObj['openid'],
                'unionid'=>$userWechatObj['unionid'],
                'data'=>json_encode([
                    'thing1' => array(
                        'value'=> $orderInfo['tips']
                    ),
                    'character_string2' => array(
                        'value'=>$orderInfo['order_no']
                    ),
                    'thing4' => array(
                        'value'=>$recevieInfo['nickname']
                    ),
                    'phone_number8' => array(
                        'value'=>$recevieInfo['mobile']
                    ),
                    'time6' => array(
                        'value'=>date('Y-m-d H:i:s',time()),
                    )
                ]),
                'status_text'=>'推送失败,原因:'.$push_result['errmsg'],
            ];
            (new MiniPushMessageLog())->create($insert_data);
        }
        $this->success($wechatInfo['openid']);
    }
}